import React, { Component } from "react";
import { connect } from "react-redux";
import { Toast, Modal } from "antd-mobile";
import Dialog from "@component/dialog/dialog";
import RepaymentSelectBank from "@component/repaymentSelectBank";
import { setDialog } from "@redux/Action/dialog/dialog";
import {
	setRepaymentMoney,
	setRepaymentParams
} from "@redux/Action/repayment/repaymentMoney";
import { getAppPlatformsDatas } from "@redux/Action/nativeDatas/nativeDatas";
import { BillHomeData } from "@redux/Action/bill/billAction";
import yhTools from "@tools/yh";
import MainLayout from "@component/mainLayout/mainLayout";
import { InterfaceG } from "@config/Config";
import { dropByCacheKey } from "react-router-cache-route";
import "./RepaymentMoney.scss";
import iconZfb from "@images/icon_zfb.png";
import icon_bank_select from "@images/icon-bank-select.png";
import icon_bank_no_select from "@images/icon-bank-no-select.png";
import { Base64 } from "js-base64";
import {
	setSelectedBankCard,
} from "@redux/Action/bank/bank";
/**
 * 小辉贷还款
 */
class RepaymentMoney extends Component {
	constructor(props) {
		super(props);
		this.timer = null;
		let pageParams = JSON.parse(this.props.match.params.data);
		this.state = {
			canNotRepayReason: "",
			showModal: false,
			pageParams: pageParams,
			amountData: null, //初始化还款页面数据
			selectedBank: null, //用户默认的还款银行卡
			souceId: "", //页面来源
			orgiTransNo: "", //订单号
			type: "", //1分期还款
			showAlipayRepaymentBtn: false,
			selectTools: {
				// 支付方式选择状态
				alipay: false,
				bankcard: false
			},
			open: false
		};
		this.submitPay = yhTools.debounce(this.submitPay, 1000);
		this.version = this.props.getAppPlatformsDatas.sdkVersionCode || "1.0.1";
	}
	componentDidMount() {
		this.getInitData(); //获取初始化数据
		this.getUserBank(); //获取默认银行卡
	}

	//获取还款页面初始化数据，例如金额，是否显示线下转账按钮
	getInitData = () => {
		//小辉贷还款
		let params;
		params = {
			url: InterfaceG.repayQuatoConfirm,
			params: {
				repayBill: this.state.pageParams.repayBill, //0 - 账单还款 ， 1- 提前结清
				loanArray: this.state.pageParams.loanArray //提前结清选择的借据号数组
			}
		};
		yhTools.request(params).then(res => {
			if (res.code == "0") {
				this.props._setRepaymentMoney({
					totalLoanFee: res.data.totalAmt,
					type: "pay"
				});
				this.setState({
					amountData: res.data.totalAmt
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	submitPay = () => {
		//小辉贷
		this.xhdPay();
	};

	//小辉贷还款
	xhdPay() {
		console.log(this.state, this.props);
		let { selectTools } = this.state;
		if (selectTools["alipay"] && yhTools.isSupportAlipay(this.version)) {
			//选择支付宝
			const params = {
				url: InterfaceG.xhdAlipayPreBackPay,
				params: {
					amount: this.state.amountData,
					cinoArray: this.state.pageParams.loanArray,
					productNum: "802", //产品大类: 小辉贷：802；好借：2000
					repayMean: "1", //还款方式，1，支付宝，2，银行卡，3，微信
					repayType: this.state.pageParams.repayBill //还款类型 ，0 - 正常还款， 1 - 提前结清
				},
				_alertShow: false
			};
			Toast.loading("正在提交中...", 10);
			yhTools
				.request(params)
				.then(res => {
					Toast.hide();
					const data = res.data;
					if (res.code === "0" && !res.data.canNotRepayReason) {
						this.repaymentAlipayClick(data);
					} else if (
						res.code === "0" &&
						res.data.canNotRepayReason &&
						res.data.canNotRepayReason != ""
					) {
						this.setState({
							canNotRepayReason: res.data.canNotRepayReason,
							showModal: true
						});
					} else {
						Toast.info(res.message, 2);
					}
				})
				.catch(() => {
					Toast.hide();
				});
		} else if (selectTools["bankcard"]) {
			//选择银行卡
			if (!this.state.selectedBank || !this.state.selectedBank.bankCode) {
				Toast.info("请先添加银行卡", 2);
				return;
			}
			dropByCacheKey("authenticatePay");
			const params = {
				url: InterfaceG.signApply,
				params: {
					bankCode: this.state.selectedBank.bankCode //银行卡Code
				},
				_alertShow: false
			};
			Toast.loading("正在提交中...", 100, () => { });
			yhTools
				.request(params)
				.then(res => {
					Toast.hide();
					const data = res.data;
					if (res.code === "0") {
						//pageIndex跳转页面:0-认证支付签约页面    1-认证支付还款页面
						const pageIndex = data.pageIndex;
						if (pageIndex == "0") {
							this.props.history.push({
								pathname: `/authenticatePay/${JSON.stringify({
									fromType: this.state.pageParams.fromType,
									repayType: this.state.pageParams.repayBill, //还款方式 ，0 - 正常还款， 1 - 提前结清
									cinoArray: this.state.pageParams.loanArray,
									orderNo: data.orderNo, //签约订单号 pageIndex=0
									bankCode: data.bankCode, //银行账户key
									amount: this.state.amountData, //还款页面反显用
									bankMobile: data.sucessPhoneNo, //银行预留手机号
									accountName: data.accountName, //账户名
									cardNo: data.cardNo, //卡号
									idNo: data.idNo, //证件号码
									bankName: this.state.selectedBank.bankName, //银行卡名
									pageParams: this.state.pageParams
								})}`
							});
						} else {
							this.getxhdRepayVeryCode(
								{
									repayType: this.state.pageParams.repayBill,
									cinoArray: this.state.pageParams.loanArray,
									bankCode: this.state.selectedBank.bankCode
								},
								data
							);
						}
					} else {
						Toast.info(res.message, 2);
					}
				})
				.catch(() => {
					Toast.hide();
				});
		}
	}
	/**
	 * 支付宝还款
	 */
	async repaymentAlipayClick(repaymentData) {
		const { requestData, orgiTransNo } = repaymentData;
		if (requestData) {
			let decRequest_data = Base64.decode(requestData);
			yhTools
				.openRepaymentAlipayView({ request_data: decRequest_data })
				.then(alipayResp => {
					if (alipayResp.status === "1000") {
						const params = {
							type: "2", //1:小辉付，2:小辉贷
							orgiTransNo //信贷交易流水号
						};
						this.props.history.push({
							pathname: "/xhfAlipayRet",
							state: { ...params, goPath: "/xhdHome" }
						});
					} else if (alipayResp.status === "8000") {
						Toast.info("正在处理中", 2);
					} else if (alipayResp.status === "4000") {
						Toast.info("还款失败", 2);
					} else if (alipayResp.status === "5000") {
						Toast.info("重复请求", 2);
					} else if (alipayResp.status === "6001") {
						let cancelParams = {
							url: InterfaceG.xhdAlipayBackPayCancle,
							params: {
								productNum: "802", //产品大类: 小辉贷：802；好借：2000
								transNo: orgiTransNo //信贷交易流水号
							},
							_alertShow: false
						};
						yhTools.request(cancelParams).then(resp => {
							if (resp.code === "0") {
								Toast.info("还款取消", 2);
							}
						});
					} else if (alipayResp.status === "6002") {
						Toast.info("网络连接出错", 2);
					}
				});
		} else {
			Toast.info("获取请求数据失败", 2);
		}
	}
	//小辉贷获取确认付款验证码
	getxhdRepayVeryCode(par, data) {
		const params = {
			url: "/xhd/loan/prePayment",
			params: {
				repayType: par.repayType,
				cinoArray: par.cinoArray,
				bankCode: par.bankCode
			},
			_alertShow: false
		};
		let _that = this;
		Toast.loading("正在提交中...", 100, () => { });
		yhTools
			.request(params)
			.then(res => {
				Toast.hide();
				if (res.code === "0" && !res.data.canNotRepayReason) {
					_that.props.history.push({
						pathname: `/backPay`,
						state: {
							fromType: _that.state.pageParams.fromType,
							repayType: _that.state.pageParams.repayBill, //发送短信手机号码 中间4位隐藏
							bankCode: _that.state.selectedBank.bankCode, //银行账户key
							cinoArray: _that.state.pageParams.loanArray,
							amount: _that.state.amountData, //还款页面反显用
							sucessPhoneNo: data.bankMobile, //银行预留手机号
							pageParams: _that.state.pageParams,
							bankMobile: data.sucessPhoneNo //银行预留手机号
						}
					});
				} else if (
					res.code === "0" &&
					res.data.canNotRepayReason &&
					res.data.canNotRepayReason != ""
				) {
					_that.setState({
						canNotRepayReason: res.data.canNotRepayReason,
						showModal: true
					});
				} else {
					Toast.info(res.message, 2);
				}
			})
			.catch(() => {
				Toast.hide();
			});
	}
	/**切换支付方式 */
	changePaytool = tool => {
		let newTool = {};
		for (let key in this.state.selectTools) {
			if (key === tool) {
				newTool[key] = true;
			} else {
				newTool[key] = false;
			}
		}
		this.setState({
			selectTools: newTool
		});
	};

	//获取默认的银行卡
	getUserBank = () => {
		const params = {
			url: InterfaceG.getUserBank,
			params: {
				type: "1", //1：默认  2：全部
				productCategory: "802" //产品大类 小辉付：601，小辉贷：802，好借：2000
			},
			_alertShow: false
		};
		yhTools.request(params).then(res => {
			if (res.code == "0") {
				let { bankCardVos, showAlipayRepaymentBtn } = res.data;
				console.log('获取卡-----：', this.props.bankReducer);
				if (this.props.bankReducer.selectedBankCard.cardNo) {
					console.log('有默认的卡')
					let bank = this.props.bankReducer.selectedBankCard;
					let _selectedBank = {
						bankAccount: bank.cardNo,
						bankCode: bank.bindCardNo,
						bankName: bank.bankName,
						logurl: bank.logoUrl,
						maxAmt: bank.dayAmount
					};
					this.setState({
						selectedBank: _selectedBank
					});
					this.changePaytool("bankcard");
				} else {
					for (let i = 0; i < bankCardVos.length; i++) {
						if (bankCardVos[i].isDefault == "1") {
							this.setState({
								selectedBank: bankCardVos[i],
							});
							this.changePaytool("bankcard");
							break;
						}
					}
				}
				const { selectedBank } = this.state;
				//默认还款方式逻辑：首先默认银行卡还款，当无绑定的银行卡，且Sdk版本支持支付宝，就默认支付宝
				//有卡就默认卡
				if (selectedBank && (selectedBank.bankCode || selectedBank.bankAccount)) {
					this.setState({
						selectTools: {
							// 支付方式选择状态
							alipay: false,
							bankcard: true
						}
					});
				} else if (
					showAlipayRepaymentBtn &&
					yhTools.isSupportAlipay(this.version) &&
					!selectedBank
				) {
					// 有支付宝就默认支付宝
					this.setState({
						selectTools: {
							// 支付方式选择状态
							alipay: true,
							bankcard: false
						}
					});
				}
				this.setState({
					showAlipayRepaymentBtn
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	//换卡
	changeBankCard = () => {
		this.setState({
			open: true
		});
	};
	handleCloseSelectBank = (type) => {
		this.setState({
			open: false
		});
		if (type == 1) {
			this.getUserBank();
		} else if (type == 3) {
			this.initStoreBank();
		}
	};
	initStoreBank = () => {
		console.log('4444444444', this.props.bankReducer)
		if (this.props.bankReducer.selectedBankCard.cardNo) {
			let bank = this.props.bankReducer.selectedBankCard;
			let _selectedBank = {
				bankAccount: bank.cardNo,
				bankCode: bank.bindCardNo,
				bankName: bank.bankName,
				logurl: bank.logoUrl,
				maxAmt: bank.dayAmount
			};
			console.log('55555555555', bank)
			this.setState({
				selectedBank: _selectedBank
			}, () => {
				console.log('666666666', this.state.selectedBank)
			});
		}
	}
	handleAddBank = () => {
		this.props.history.push(`/xhdAddBank?from=01`);
		// this.props._setRepaymentParams({
		// 	...this.state.pageParams
		// });
	};
	gobcakHome() {
		this.props.history.push("/xhdHome");
	}
	render() {
		let {
			amountData,
			selectedBank,
			showAlipayRepaymentBtn,
			selectTools
		} = this.state;
		// let souceId = this.props.loanProcessDataReducer.souceId;
		// let pathNameParams = this.state.pageParams.backPath;

		const headerParams = {
			header: {
				title: "还款",
				headerBackground: "#fff",
				titleColor: "#232323",
				newBackButt: true,
				// goBackPath: "/" + pathNameParams,
				fromPage: "repaymentMoney"
			},
			history: this.props.history,
			loadStatus: this.state.loadStatus, // （ '0'：数据加载中，'1'：加载完成，'2'：加载失败）
			cacheLifecycles: this.props.cacheLifecycles
		};
		return (
			<MainLayout pageParams={headerParams}>
				<div className={"repayment-money-page"}>
					<div className="content-body" id="contentBody">
						<div className="top-money">
							<div className="money-tips">还款金额(元)</div>
							<div className="money-num">{amountData ? amountData : "--"}</div>
						</div>
						<div className="center-bank">
							<div className="bank-top">
								<div className="top-left">银行卡还款</div>
								{selectedBank && (
									<img
										className="item-right-arrow"
										src={
											selectTools.bankcard
												? icon_bank_select
												: icon_bank_no_select
										}
										onClick={() => this.changePaytool("bankcard")}
									/>
								)}
							</div>

							{selectedBank && (
								<div style={{ width: "100%" }}>
									<div
										className="bank-item"
										onClick={() => this.changePaytool("bankcard")}
									>
										<img className="item-left-img" src={selectedBank.logurl} />
										<div className="item-center">
											<div className="center-top">
												{selectedBank.bankName +
													"(" +
													selectedBank.bankAccount +
													")"}
											</div>
										</div>
									</div>
									<div
										className="change-content"
										onClick={this.changeBankCard.bind(this)}
									>
										<div className="bank-right">切换其他银行卡支付</div>
										<img
											className="item-right-arrow"
											src={require("../../../images/icon-arrorw-right.png")}
										/>
									</div>
								</div>
							)}
							{!selectedBank && (
								<img
									className="add-bank-btn-bg"
									src={require("@images/add-bank-btn-bg.png")}
									alt=""
									onClick={this.handleAddBank}
								/>
							)}
						</div>
						{showAlipayRepaymentBtn && yhTools.isSupportAlipay(this.version) && (
							<div
								style={{ marginTop: "0.2rem" }}
								className="zfb-item"
								onClick={() => this.changePaytool("alipay")}
							>
								<img className="item-left-img" src={iconZfb} />
								<div className="pay-label">支付宝还款</div>
								<img
									className="item-right-arrow"
									src={
										selectTools.alipay ? icon_bank_select : icon_bank_no_select
									}
								/>
							</div>
						)}
						<div className="submit-div">
							<a
								className="submit-btn a-gradient"
								id="bottomDom"
								onClick={this.submitPay}
							>
								确认还款
							</a>
						</div>
					</div>
					<Dialog propsObj={this.props} />
					<Modal
						className="repay-tip-modal"
						visible={this.state.showModal}
						transparent
						maskClosable={false}
						footer={[
							{
								text: "返回首页",
								onPress: () => {
									this.gobcakHome();
								}
							}
						]}
					>
						<div style={{ height: "1rem" }}>{this.state.canNotRepayReason}</div>
					</Modal>
				</div>
				<RepaymentSelectBank
					value={selectedBank}
					open={this.state.open}
					close={this.handleCloseSelectBank}
					add={this.handleAddBank}
				>
					<span></span>
				</RepaymentSelectBank>
			</MainLayout>
		);
	}
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps(dispatch) {
	return {
		_setDialog: options => {
			dispatch(setDialog(options));
		},
		_setRepaymentMoney: options => {
			dispatch(setRepaymentMoney(options));
		},
		_setRepaymentParams: options => {
			dispatch(setRepaymentParams(options));
		},
		_getAppPlatformsDatas: options => {
			dispatch(getAppPlatformsDatas(options));
		},
		_setSelectedBankCard: value => dispatch(setSelectedBankCard(value)),
		_billHomeData: options => {
			//存入redux
			dispatch(BillHomeData(options));
		}
	};
}

const RepaymentMoneyPage = connect(
	mapStateToProps,
	mapDispatchToProps
)(RepaymentMoney);
export default RepaymentMoneyPage;
